#include "gps.h"
#include "gpio.h"
#include "usart.h"
#include "rtc.h"
#include "usart.h"
#include "eeprom.h"
#include "tracking.h"
#include "system.h"
#include <string.h>
//#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define false 0
#define true 1
//定义数组长度
#define GPS_Buffer_Length 80
#define UTCTime_Length 11
#define latitude_Length 11
#define N_S_Length 2
#define longitude_Length 12
#define E_W_Length 2 	
#define USART_REC_LEN  			200  	   //定义最大接收字节数 200	

uint8_t USART_RX_BUF[USART_REC_LEN]; //接收缓冲,最大USART_REC_LEN个字节.
uint16_t point1 = 0;                 //记录数据起点

typedef struct SaveData 
{
	char GPS_Buffer[GPS_Buffer_Length];
	char isGetData;		//是否获取到GPS数据
	char isParseData;	//是否解析完成
	char UTCTime[UTCTime_Length];		//UTC时间
	char latitude[latitude_Length];		//纬度
	char N_S[N_S_Length];		//N/S
	char longitude[longitude_Length];		//经度
	char E_W[E_W_Length];		//E/W
  char date[8];	
	char isUsefull;		//定位信息是否有效
} _SaveData;

_SaveData Save_Data;

float    latitude_gps; //经度
float    longitude_gps;//纬度
int16_t  time_zone;//时区

DTL local_time;
DTL gps_time;

void errorLog(int num)
{

}


void GPS_ParseBuffer()
{
	char *subString;
	char *subStringNext;
	char i = 0;
	if (Save_Data.isGetData)
	{
		Save_Data.isGetData = false;

		for (i = 0 ; i <= 9 ; i++)
		{
			if (i == 0)
			{
				if ((subString = strstr(Save_Data.GPS_Buffer, ",")) == NULL)
					errorLog(1);	//解析错误
			}
			else
			{
				subString++;
				if ((subStringNext = strstr(subString, ",")) != NULL)
				{
					char usefullBuffer[2]; 
					switch(i)
					{
						case 1:memcpy(Save_Data.UTCTime, subString, subStringNext - subString);break;	  //获取UTC时间
						case 2:memcpy(usefullBuffer, subString, subStringNext - subString);break;	      //获取UTC时间
						case 3:memcpy(Save_Data.latitude, subString, subStringNext - subString);break;	//获取纬度信息
						case 4:memcpy(Save_Data.N_S, subString, subStringNext - subString);break;	      //获取N/S
						case 5:memcpy(Save_Data.longitude, subString, subStringNext - subString);break;	//获取经度信息
						case 6:memcpy(Save_Data.E_W, subString, subStringNext - subString);break;	      //获取E/W
            case 9:memcpy(Save_Data.date, subString, subStringNext - subString);break;      //获取日期		
						default:break;
					}

					subString = subStringNext;
					Save_Data.isParseData = true;
					if(usefullBuffer[0] == 'A')
						Save_Data.isUsefull = true;
					else if(usefullBuffer[0] == 'V')
						Save_Data.isUsefull = false;

				}
				else
				{
					errorLog(2);	//解析错误
				}
			}


		}
		if(Save_Data.isUsefull == true)
		{
				float d_lon = 0.0;
				float d_lat = 0.0;
				float d_tmp1 = 0.0;
				float d_tmp2 = 0.0;
			
				d_lat = atof(Save_Data.latitude);
				d_lat /= 100;
				d_tmp1 = floor(d_lat);
				d_tmp2 = d_lat - d_tmp1;
				d_tmp2 *= 100;
				d_tmp2 /= 60;
				d_lat = d_tmp1 + d_tmp2;
				d_lat=( (float)( (int)( (d_lat+0.005)*100 ) ) )/100;  //小数点取2位

				d_lon = atof(Save_Data.longitude);
				d_lon /= 100;
				d_tmp1 = floor(d_lon);
				d_tmp2 = d_lon - d_tmp1;
				d_tmp2 *= 100;
				d_tmp2 /= 60;
				d_lon = d_tmp1 + d_tmp2;
				d_lon=( (float)( (int)( (d_lon+0.005)*100 ) ) )/100;  //小数点取2位

			 if(Save_Data.N_S[0] == 'N')
			 {
					 latitude_gps = d_lat;
			 }
			 else if(Save_Data.N_S[0] == 'S')
			 {
					 latitude_gps = (-1) * d_lat;
			 }

			 if(Save_Data.E_W[0] == 'E')
			 {
					 longitude_gps = d_lon;
			 }
			 else if(Save_Data.E_W[0] == 'W')
			 {
					 longitude_gps = (-1)* d_lon;
			 }
			 
//			 latitude_gps = (-1) * latitude_gps;
//			 longitude_gps = (-1)* longitude_gps;
             
                

			 gps_time.hour  =(Save_Data.UTCTime[0]-0x30)*10+(Save_Data.UTCTime[1]-0x30);
			 gps_time.minute=(Save_Data.UTCTime[2]-0x30)*10+(Save_Data.UTCTime[3]-0x30);
			 gps_time.second=(Save_Data.UTCTime[4]-0x30)*10+(Save_Data.UTCTime[5]-0x30);

			 gps_time.day   =(Save_Data.date[0]-0x30)*10+(Save_Data.date[1]-0x30);
			 gps_time.month =(Save_Data.date[2]-0x30)*10+(Save_Data.date[3]-0x30);
			 gps_time.year  =(Save_Data.date[4]-0x30)*10+(Save_Data.date[5]-0x30)+2000;
			 
			 UTC_to_LocalTime(&gps_time, (int16_t)stSYS.TimeZone);
	
	     Modbus_Output_Reg[3] = local_time.year;  //年
       Modbus_Output_Reg[4] = local_time.month; //月
       Modbus_Output_Reg[5] = local_time.day;   //日
       Modbus_Output_Reg[6] = local_time.hour;  //时
       Modbus_Output_Reg[7] = local_time.minute;//分
       Modbus_Output_Reg[8] = local_time.second;//秒			
			 
       Modbus_Output_Reg[9] =(uint16_t)((int16_t)(longitude_gps*100));	//经度
       Modbus_Output_Reg[10]=(uint16_t)((int16_t)(latitude_gps*100));	//纬度				 

			 memset(USART_RX_BUF, 0, sizeof(USART_RX_BUF));
		}		
	}
}

void GPS_Callback(void)//GPS中断服务程序
{
	uint8_t Res;
	
	Res=bUART3_tmp;//读取接收到的数据
	if(Res == '$')
	{
		point1 = 0;	
	}

	USART_RX_BUF[point1++] = Res;

	if( (USART_RX_BUF[0] == '$') && (USART_RX_BUF[4] == 'M') && (USART_RX_BUF[5] == 'C') )			//确定是否收到"GPRMC/GNRMC"这一帧数据
	{
		if(Res == '\n')									   
		{
			memset(Save_Data.GPS_Buffer, 0, GPS_Buffer_Length);      //清空
			memcpy(Save_Data.GPS_Buffer, USART_RX_BUF, point1); 	//保存数据
			Save_Data.isGetData = true;
			point1 = 0;
			memset(USART_RX_BUF, 0, USART_REC_LEN);      //清空				
		}	
	}
	
	if(point1 >= USART_REC_LEN)
	{
		point1 = USART_REC_LEN;
	}	
}




void UTC_to_LocalTime(DTL*	utc_time, int8_t	timezone)
{
	int year,month,day,hour;
    int lastday = 0;					//last day of this month
    int lastlastday = 0;			//last day of last month

    year	 = utc_time->year;			 //utc time
    month  = utc_time->month;
    day 	 = utc_time->day;
    hour 	 = utc_time->hour + timezone; 
	
    if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
        lastday = 31;
        if(month == 3){
            if((year%400 == 0)||(year%4 == 0 && year%100 != 0))				//if this is lunar year
                lastlastday = 29;
            else
                lastlastday = 28;
        }
        if(month == 8)
            lastlastday = 31;
				if(month == 1)//WHL一月的上一个月是十二月，十二月是31天
					  lastlastday = 31;
				if(month==5 || month==7 || month==10 || month==12)//WHL上个月是30天
						lastlastday = 30;
    }
    else if(month == 4 || month == 6 || month == 9 || month == 11){
        lastday = 30;
        lastlastday = 31;
    }
    else{  //这是二月份
        lastlastday = 31;
        if((year%400 == 0)||(year%4 == 0 && year%100 != 0))
            lastday = 29;
        else
            lastday = 28;
    }

    if(hour >= 24){					// if >24, day+1
            hour -= 24;
            day += 1; 

            if(day > lastday){ 		// next month,  day-lastday of this month
                day -= lastday;
                month += 1;

                if(month > 12){		//	next year , month-12
                    month -= 12;
                    year += 1;
                }
            }
        }
    if(hour < 0){										// if <0, day-1
            hour += 24;
            day -= 1; 
            if(day < 1){					  // month-1, day=last day of last month
                day = lastlastday;
                month -= 1;
                if(month < 1){ 			// last year , month=12
                    month = 12;
                    year -= 1;
                }
            }
        }
   // transfer value to NMEA_result.local_time
	local_time.year   = year;
	local_time.month  = month;
	local_time.day    = day;
	local_time.hour   = hour;
	local_time.minute	= utc_time->minute;
	local_time.second	= utc_time->second;
}
